import { defineStore } from 'pinia'
import { ref } from 'vue'
import { authApi, type User } from '@/api/auth'
import { ElMessage } from 'element-plus'

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null)
  const token = ref<string | null>(null)
  const isTestMode = ref(false)

  // 测试用户数据
  const testUser: User = {
    id: 1,
    username: 'test_admin',
    role: 'admin',
    created_at: '2024-01-01T00:00:00'
  }

  // 初始化状态
  const initAuth = () => {
    const storedToken = localStorage.getItem('token')
    const storedUser = localStorage.getItem('user')
    const testMode = localStorage.getItem('testMode') === 'true'
    
    if (testMode) {
      isTestMode.value = true
      user.value = testUser
      token.value = 'test-token'
      return
    }
    
    if (storedToken && storedUser) {
      token.value = storedToken
      user.value = JSON.parse(storedUser)
    }
  }

  // 登录
  const login = async (username: string, password: string) => {
    // 测试模式登录
    if (username === 'test_admin' && password === 'test123') {
      isTestMode.value = true
      user.value = testUser
      token.value = 'test-token'
      
      localStorage.setItem('token', 'test-token')
      localStorage.setItem('user', JSON.stringify(testUser))
      localStorage.setItem('testMode', 'true')
      
      ElMessage.success('测试模式登录成功')
      return true
    }

    try {
      const response = await authApi.login({ username, password })
      token.value = response.token
      user.value = response.user
      
      localStorage.setItem('token', response.token)
      localStorage.setItem('user', JSON.stringify(response.user))
      localStorage.setItem('testMode', 'false')
      
      ElMessage.success('登录成功')
      return true
    } catch (error) {
      ElMessage.error('登录失败')
      return false
    }
  }

  // 注册
  const register = async (username: string, password: string, role: string = 'student') => {
    try {
      await authApi.register({ username, password, role })
      ElMessage.success('注册成功，请登录')
      return true
    } catch (error) {
      ElMessage.error('注册失败')
      return false
    }
  }

  // 注册管理员账号
  const registerAdmin = async (username: string, password: string, name: string = '', email: string = '') => {
    try {
      await authApi.registerAdmin({ username, password, name, email })
      ElMessage.success('管理员账号注册成功，请登录')
      return true
    } catch (error) {
      ElMessage.error('注册失败')
      return false
    }
  }

  // 注册学生账号（需要管理员或教师权限）
  const registerStudent = async (username: string, password: string, name: string, email: string = '') => {
    try {
      await authApi.register({ username, password, name, email, role: 'student' })
      return true
    } catch (error) {
      throw error
    }
  }

  // 批量注册学生账号
  const registerBatchStudents = async (students: Array<{username: string, password?: string, name: string, email?: string}>) => {
    try {
      const response = await authApi.registerBatch({ students })
      return response
    } catch (error) {
      throw error
    }
  }

  // 登出
  const logout = () => {
    user.value = null
    token.value = null
    isTestMode.value = false
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    localStorage.removeItem('testMode')
    ElMessage.success('已退出登录')
  }

  // 获取用户信息
  const fetchProfile = async () => {
    if (isTestMode.value) {
      return
    }
    
    try {
      const profile = await authApi.getProfile()
      user.value = profile
      localStorage.setItem('user', JSON.stringify(profile))
    } catch (error) {
      logout()
    }
  }

  // 修改密码
  const changePassword = async (oldPassword: string, newPassword: string) => {
    if (isTestMode.value) {
      ElMessage.success('测试模式：密码修改成功')
      return true
    }
    
    try {
      await authApi.changePassword({ old_password: oldPassword, new_password: newPassword })
      ElMessage.success('密码修改成功')
      return true
    } catch (error) {
      ElMessage.error('密码修改失败')
      return false
    }
  }

  // 检查是否已登录
  const isLoggedIn = () => {
    return !!token.value && !!user.value
  }

  // 检查权限
  const hasRole = (role: string) => {
    return user.value?.role === role
  }

  const hasAnyRole = (roles: string[]) => {
    return user.value ? roles.includes(user.value.role) : false
  }

  // 检查是否为测试模式
  const getIsTestMode = () => {
    return isTestMode.value
  }

  return {
    user,
    token,
    isTestMode,
    initAuth,
    login,
    register,
    registerAdmin,
    registerStudent,
    registerBatchStudents,
    logout,
    fetchProfile,
    changePassword,
    isLoggedIn,
    hasRole,
    hasAnyRole,
    getIsTestMode
  }
})
